package hibernateDAOS;

import hibernate.HibernateUtil;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;


import beans.Comanda;
import beans.ItemComanda;
import beans.Mozo;

public class ComandaDAO {
	
	private static ComandaDAO instancia = null;
	private static SessionFactory sf = null;

	public static ComandaDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new ComandaDAO();
		} 
		return instancia;
	}
	
	public void guardarComanda(Comanda c){
		Session session = sf.openSession();
		session.beginTransaction();
		for ( ItemComanda ic : c.getItemsComanda()){
			session.save(ic);
		}
		session.save(c);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void eliminarComanda(Comanda c){
		Session session = sf.openSession();
		session.beginTransaction();
		session.delete(c);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	public void modificarComanda(Comanda c){
		Session session = sf.openSession();
		session.beginTransaction();
		session.saveOrUpdate(c);
		session.flush();
		session.getTransaction().commit();
		session.close();
	}

	@SuppressWarnings("unchecked")
	public List<Object[]> obtenerComandas(String rubro){
		Session session = sf.openSession();
		Query q = session.createQuery("from Comanda where Rubro='"+rubro+"'");
		List<Comanda> comandas = q.list();
		Object[] o;
		List<Object[]> lista = new ArrayList<Object[]>();
		for(Comanda c : comandas){
			o = new Object[5] ;
			o[0] = (Object) c.getNroComanda();
			o[1] = (Object) c.getMozo().getNombre();
			o[2] = (Object) c.getMesa().getnroMesa();
			o[3] = (Object) c.getMesa().getNroSector();
			lista.add(o);
		}
		
		session.close();
		return lista;
	}
	
	@SuppressWarnings("unchecked")
	public List<Object[]> obtenerComisionesMozos(){
		Session session = sf.openSession();
		Query q = session.createQuery("from Comanda c join c.mozos");
		List<Object[]> comisiones = q.list();
		session.close();
		return comisiones;
	}
	@SuppressWarnings("unchecked")
	public Object[] obtenerComanda(Comanda c){
		Session session = sf.openSession();
		session.load(c, c.getNroComanda());
		
		Object[] o = new Object[5] ;
		o[0] = (Object) c.getNroComanda();
		o[1] = (Object) c.getMozo().getNombre();
		o[2] = (Object) c.getMesa().getnroMesa();
		o[3] = (Object) c.getMesa().getNroSector();
		String platosConcatenados="";
		for (ItemComanda ic :  c.getItemsComanda()){
			platosConcatenados+=ic.getPlato().getNombrePlato()+"<br />";
		}
		o[4] = (Object) platosConcatenados;
		
		session.close();
		return o;
	}
}


